<?php

namespace App\Http\Controllers\User;

use App\Http\Requests\ChangePassword;
use App\Http\Requests\UserPost;
use App\Model\User\AuthGroup;
use App\Model\User\User;
use Exception;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {
            $input = $request->all();
            if (Auth::user()->is_superuser) {
                if (empty($input['group'])) {
                    $users = User::where('username', 'like', '%' . $input['username'] . '%')
                        ->with('groups')->orderBY('created_at', 'desc')->paginate($input['page_size']);
                } else {
                    $users = User::where('username', 'like', '%' . $input['username'] . '%')
                        ->with('groups')
                        ->whereHas('groups', function ($query) use ($input) {
                            $query->where('group_id', $input['group']);
                        })->orderBY('created_at', 'desc')->paginate($input['page_size']);
                }
            } else {
                $users = User::where('username', Auth::user()->username)->with('groups')
                    ->orderBY('created_at', 'desc')->paginate($input['page_size']);
            }
            return $this->success(200, $users);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param UserPost $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserPost $request)
    {
        $validator = $request->validated();
        $input = $request->all();
        $input['username'] = strval($input['username']);
        $input['password'] = bcrypt($input['password']);
        $uniquename = User::where('username', '=', $input['username'])->get();
        if (sizeof($uniquename)) {
            return $this->fail(500, ['message' => '该用户名已经注册，请重新填写~~~']);
        } else {
            DB::transaction(function () use ($input) {
                $user = User::create($input);
                $user->meal_supplement_balance()->create([
                    'user_id' => $user->id,
                    'meal_supplement_balance' => 0
                ]);
                return $this->success(200, $user);
            }, 5);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $user = User::find($id);
            $group = $user->groups()->orderBy('name')->get();
            $user['groups'] = $group;
            return $this->success(200, $user);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->all();
        $user = User::find($id);
        if (Auth::user()->is_superuser) {
            $user->username = $input['username'];
            $user->is_superuser = $input['is_superuser'];
            $user->is_staff = $input['is_staff'];
            $user->is_active = $input['is_active'];
            $user->groups()->sync($input['groups']);
        }
        $user->first_name = $input['first_name'];
        $user->save();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $user = User::find($id);
            $user->delete();
            return $this->success(204);
        } catch (Exception $e) {
            return $this->fail(500, ['Message ' => $e->getMessage()]);
        }
    }

    public function changePassword(ChangePassword $request)
    {
        $validator = $request->validated();
        $input = $request->all();
        $user = Auth::user();
        $password = $user->getAuthPassword();
//        $token = $user->token();
        if (!Hash::check($input['oldPassword'], $password)) {
            return $this->success(422, ['Message' => '原密码密码不正确']);
        } else {
            $user->password = Hash::make($input['newPassword']);
            $user->save();
            $user->token()->delete();
            return $this->success(200, ['data' => '密码修改成功！']);
        }
    }
}
